import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
from PIL import Image, ImageTk
from datetime import datetime
import glob


def read_comic(root , selected_comics , cursor):
    if not selected_comics:
        messagebox.showwarning("警告", "请先选择一个漫画！")
        return
    
    comic_id = next(iter(selected_comics))
    cursor.execute("SELECT folder_path FROM comics WHERE id=?", (comic_id,))
    folder_path = cursor.fetchone()[0]
    
    # 创建阅读窗口
    reader = tk.Toplevel(root)
    reader.title("漫画阅读器")
    reader.geometry("1000x700")
    
    # 获取图片列表
    image_files = []
    for ext in ["*.jpg", "*.jpeg", "*.png", "*.gif"]:
        image_files.extend(glob.glob(os.path.join(folder_path, "**", ext), recursive=True))
    
    if not image_files:
        tk.Label(reader, text="未找到图片文件", padx=20, pady=20).pack()
        return
    
    image_files.sort()
    current_index = 0
    
    # 显示区域
    img_frame = tk.Frame(reader, bg="#2c3e50")
    img_frame.pack(fill="both", expand=True, padx=10, pady=10)
    
    img_label = tk.Label(img_frame)
    img_label.pack(fill="both", expand=True)
    
    # 章节列表
    chapters = []
    for root, dirs, files in os.walk(folder_path):
        if root != folder_path:
            chapters.append(root)
    
    chapter_frame = None
    if chapters:
        chapter_frame = tk.Frame(reader, bg="#34495e")
        chapter_frame.pack(fill="x", padx=10, pady=(0, 10))
        
        tk.Label(chapter_frame, text="章节列表:", bg="#34495e", fg="white").pack(side="left", padx=5)
        
        for i, chapter in enumerate(chapters):
            chapter_name = os.path.basename(chapter)
            btn = tk.Button(chapter_frame, text=chapter_name, 
                            command=lambda c=chapter: load_chapter(c, img_label))
            btn.pack(side="left", padx=2)
    
    # 控制栏
    ctrl_frame = tk.Frame(reader, bg="#34495e")
    ctrl_frame.pack(fill="x", padx=10, pady=10)
    
    prev_btn = tk.Button(ctrl_frame, text="上一页", 
                        command=lambda: change_image(-1, image_files, current_index, img_label))
    prev_btn.pack(side="left", padx=10)
    
    next_btn = tk.Button(ctrl_frame, text="下一页", 
                        command=lambda: change_image(1, image_files, current_index, img_label))
    next_btn.pack(side="left", padx=10)
    
    # 加载第一张图片
    load_image(image_files[current_index], img_label)

def load_chapter(chapter_path, img_label):
        image_files = []
        for ext in ["*.jpg", "*.jpeg", "*.png", "*.gif"]:
            image_files.extend(glob.glob(os.path.join(chapter_path, ext)))
        
        if image_files:
            image_files.sort()
            load_image(image_files[0], img_label)

def change_image(direction, image_files, current_index, img_label):
        current_index = max(0, min(len(image_files) - 1, current_index + direction))
        load_image(image_files[current_index], img_label)
        return current_index

def load_image(path, label):
        try:
            img = Image.open(path)
            # 调整大小以适应窗口
            img.thumbnail((900, 600))
            photo = ImageTk.PhotoImage(img)
            label.config(image=photo)
            label.image = photo
        except Exception as e:
            print(f"加载图片错误: {e}")